<template>
  <div class="screen-list-page">
    <div class="op-bar">
      <el-input
        v-model="searchKeyword"
        placeholder="搜索大屏名称/描述"
        style="width:220px"
        @input="filterScreens"
        clearable
      />
      <el-select
        v-model="selectedGroup"
        placeholder="分组"
        style="width:140px"
        @change="filterScreens"
        clearable
      >
        <el-option label="全部分组" value="" />
        <el-option v-for="g in groupOptions" :key="g" :label="g" :value="g" />
      </el-select>
      <el-button type="primary" @click="goDesigner()">新建大屏</el-button>
      <el-button @click="exportScreensExcel">导出为Excel</el-button>
    </div>
    <el-table :data="filteredScreens" border style="margin-top:14px">
      <el-table-column prop="name" label="大屏名称" min-width="130" />
      <el-table-column prop="group" label="分组" min-width="100" />
      <el-table-column prop="desc" label="描述" min-width="220" />
      <el-table-column prop="theme" label="主题" min-width="90" />
      <el-table-column prop="created" label="创建时间" width="110" />
      <el-table-column label="操作" width="230">
        <template #default="scope">
          <el-button size="small" @click="goPreview(scope.row)">预览</el-button>
          <el-button size="small" @click="goDesigner(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteScreen(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import * as XLSX from 'xlsx'
import { ElMessage } from 'element-plus'

// 分组选项
const groupOptions = ['生产', '能耗', '销售', '设备', '管理']

// 模拟大屏数据
function mockScreens() {
  const arr = []
  for (let i = 0; i < 8; i++) {
    arr.push({
      id: Date.now() + i,
      name: ['产线大屏', '能耗监控', '销售总览', '设备监控', '管理驾驶舱', '设备工艺大屏', '实时告警大屏', '工厂综合大屏'][i],
      group: groupOptions[i % groupOptions.length],
      desc: `这是${groupOptions[i % groupOptions.length]}相关的可视化大屏，用于业务监控与展示。`,
      theme: ['深色', '浅色', '科技蓝', '简约白'][i % 4],
      created: `2024-07-${String(10 + i).padStart(2, '0')}`,
      config: {} // 设计器的数据，后续扩展
    })
  }
  return arr
}

function initScreens() {
  const local = localStorage.getItem('screens')
  if (local) return JSON.parse(local)
  const mock = mockScreens()
  localStorage.setItem('screens', JSON.stringify(mock))
  return mock
}

const screens = ref(initScreens())
const searchKeyword = ref('')
const selectedGroup = ref('')
const filteredScreens = ref([...screens.value])
const router = useRouter()

function filterScreens() {
  let arr = screens.value
  if (searchKeyword.value) {
    arr = arr.filter(s => s.name.includes(searchKeyword.value) || s.desc.includes(searchKeyword.value))
  }
  if (selectedGroup.value) {
    arr = arr.filter(s => s.group === selectedGroup.value)
  }
  filteredScreens.value = arr
}

onMounted(() => {
  screens.value = initScreens()
  filterScreens()
})

// 跳转到设计器（新建或编辑）
function goDesigner(row) {
  if (row) {
    router.push({ name: 'ScreenDesigner', params: { id: row.id } })
  } else {
    router.push({ name: 'ScreenDesigner' })
  }
}

// 跳转到预览页
function goPreview(row) {
  router.push({ name: 'ScreenPreview', params: { id: row.id } })
}

// 删除
function deleteScreen(row) {
  screens.value = screens.value.filter(s => s.id !== row.id)
  localStorage.setItem('screens', JSON.stringify(screens.value))
  filterScreens()
  ElMessage.success('已删除')
}

// 导出为Excel
function exportScreensExcel() {
  const excelData = screens.value.map(s => ({
    '大屏名称': s.name,
    '分组': s.group,
    '描述': s.desc,
    '主题': s.theme,
    '创建时间': s.created
  }))
  const ws = XLSX.utils.json_to_sheet(excelData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '大屏列表')
  XLSX.writeFile(wb, 'screens.xlsx')
}
</script>

<style scoped>
.screen-list-page {
  padding: 24px;
}
.op-bar {
  margin-bottom: 12px;
  display: flex;
  gap: 12px;
  align-items: center;
}
</style>
